<?php

/**
 * 控制器基类，里面后一些控制器的通用方法
 * @author lijun10
 *
 */
class Uuch_BaseController extends Zend_Controller_Action {

    //private $cdn = 'http://cdn.uuch.com';
    private $cdn = '';

    const COOKIE_USERNAME = '__xxnnx';
    const COOKIE_IP = '__xxppx';
    const COOKIE_TIME = '__xxttx';

    /**
     * Google分析里面定义的用户来源字段
     */
    const QUERY_STRING_SOURCE = '_s';
    const COOKIE_SOURCE = '_source';

    public function init() {
        parent::init();
        $this->view->mainnav = $this->getRequest()->getParam('controller');
        $this->view->mainnav2 = $this->_getParam('action');

        
        $this->view->mainCount = 0;
        $isLogin = $this->isLogin();
        if ($isLogin) {
            $this->view->user = $this->currentUser();
            $this->view->mainCount = Application_Model_Mail::getUnRead($this->currentUser()->id);
        } else {
            $this->view->user = new Application_Model_User(array('email' => 'None', 'Id' => 0));
        }

        $this->view->isLogin = $isLogin;

        $this->view->cnd_org = $this->cdn;
        $this->view->cdn = $this->cdn;
        $ipItem = new Application_Model_ip();
        $ip = Uuch_Util::real_ip();
        $this->view->CountryName = $ipItem->convertip($ip);
        $this->view->customVar = new Uuch_CustomVar();
        $this->setGaCustomVar(5, $this->view->mainnav . '_' . $this->view->mainnav2, 'ture', Uuch_CustomVar::LEVEL_page);

        //设置Google分析相关属性

        if (array_key_exists(self::COOKIE_SOURCE, $_COOKIE)) {
            $this->setGaCustomVar(3, Uuch_CustomVar::NAME_SOURCE, $_COOKIE[self::COOKIE_SOURCE], Uuch_CustomVar::LEVEL_visitor);
        } else {
            $source = $this->getSafeParam(self::QUERY_STRING_SOURCE);
            if (!$source && $this->isLogin()) {
                $source = $this->currentUser()->Source;
            }
            if ($source) {
                setcookie(self::COOKIE_SOURCE, $source, time() + 3600 * 24 * 7);
                $this->setGaCustomVar(3, Uuch_CustomVar::NAME_SOURCE, $source, Uuch_CustomVar::LEVEL_visitor);
            }
        }
    }

    /**
     * 记录日志
     * @param type 日志信息
     * @param Zend_Log $priority 级别
     * @param type $extras 参数
     */
    protected function _log($message, $priority, $extras = null) {
        $log = $this->getLog();
        if ($log) {
            $log->log($message, $priority, $extras);
        }
    }

    public function getLog() {

        return ($log = $this->getInvokeArg('bootstrap')->getResource('Log')) ? $log : false;
    }

    /**
     * 设置网页标题
     * @param type $title
     */
    protected function setTitle($title) {
        $this->view->title = $title;
    }

    /**
     * 设置Google分析自定义代码,不要使用3,4，5三个位置，4号位用来标记是否会员，5号位用来标志访问了哪些页面,3用于标记用户来源
     * @param int $index 分析代码位置，值只能是1到5之间，同一页上不能重复,不要使用3,4，5三个位置
     * @param string $name 变量名
     * @param string $value 值
     * @param int $level 变量级别
     */
    protected function setGaCustomVar($index, $name, $value, $level) {
        $this->view->customVar->setVar($index, $name, $value, $level);
    }

    /**
     * 设置登录用户信息
     * @param type $userName
     * @param type $remember
     */
    protected function setUser($userName, $remember) {
        $expire = 0;
        if ($remember) {
            $expire = time() + 30 * 3600 * 24;
        }

        $ip = Uuch_Util::real_ip();
        $date = date('Y-m-d');
        if ($userName == '') {
            $ip = '';
            $date = '';
        }
        setcookie(self::COOKIE_TIME, Uuch_Util::encryptString($date), $expire, "/");
        setcookie(self::COOKIE_IP, Uuch_Util::encryptString($ip), $expire, "/");
        setcookie(self::COOKIE_USERNAME, Uuch_Util::encryptString($userName), $expire, "/");
    }

    protected function getUserName() {
        return Uuch_BaseController::getCurrentUserName();
    }

    /**
     * 返回当前登录的用户名
     * @return null
     */
    public static function getCurrentUserName() {
        if (!array_key_exists(self::COOKIE_USERNAME, $_COOKIE))
            return NULL;
        $__username = $_COOKIE[self::COOKIE_USERNAME];
        return Uuch_Util::decryptString($__username);
    }

    /**
     * 是否登录
     * @return boolean
     */
    protected function isLogin() {
        if (!array_key_exists(self::COOKIE_USERNAME, $_COOKIE)) {
            return FALSE;
        }

        if (!array_key_exists(self::COOKIE_IP, $_COOKIE)) {
            return FALSE;
        }

        if (!array_key_exists(self::COOKIE_TIME, $_COOKIE)) {
            return FALSE;
        }

        $username = $this->getUserName();
        if ($username == NULL) {
            return FALSE;
        }

        //$ip = Uuch_Util::decryptString($_COOKIE[self::COOKIE_IP]);
        //if($ip != Uuch_Util::real_ip()){
        //    return FALSE;
        //}

        $lastTime = Uuch_Util::decryptString($_COOKIE[self::COOKIE_TIME]);
        $expriedTime = date('Y-m-d', time() - 24 * 60 * 60 * 30);
        if ($lastTime < $expriedTime) {
            return FALSE;
        }


        return TRUE;
    }

    /**
     *  检查登录状态，如果没有登录，就重定向到登录页，登录后跳回来
     */
    protected function checkLogin() {
        if (!$this->isLogin()) {
            //$request = $this->getRequest();
            $url = $this->curPageURL();
            //$this->_helper->redirector('login','user',NULL,array('returnUrl'=>$url));
            $this->_redirect('/User/login?returnUrl=' . urlencode($url));
            return FALSE;
        } else {
            $userItem = $this->currentUser();
            if ($userItem->lastLogin < date("Y-m-d")) {
                $accountItem = Application_Model_UserAccount::addAccount($userItem->Id);
                $accountItem->TaskExchangeScore(Application_Model_Task::TASK_LOGIN);
                $userItem->lastLogin = date("Y-m-d H:i:s");
                $userItem->save();
                $userItem->getbyip();
            }
            return TRUE;
        }
    }

    private $_currentUser = null;

    /**
     * 返回当前登录用户
     * @return Application_Model_User
     */
    public function currentUser() {

        if ($this->_currentUser == null)
            $this->_currentUser = Application_Model_User::getByEmail($this->getUserName());

        return $this->_currentUser;
    }

    /**
     * 每页显示数据条数
     * @var int
     */
    protected $pageSize = 10;

    /**
     * 读取分页控件中的开始条数
     */
    protected function getStart() {
        $start = $this->getRequest()->getParam('start', 0);
        return intval($start);
    }

    /**
     * 往头部添加一个js文件
     * 这样封装的好处是将来我们可以直接在这个位置统一将所有的文件都换到别的域名上
     * 如jquery,可以用微软的CDN服务，或者我们自己布一个静态文件服务器
     * @param string $file
     * @return Uuch_BaseController
     */
    public function appendScript($file) {
        if ($file == "/js/jquery.min.js") {
            $this->view->headScript()->appendFile('http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.1.min.js');
            return $this;
        } else {
            $temp = $this->cdn . strtolower($file);
            $this->view->headScript()->appendFile($temp);
            return $this;
        }
    }

    /**
     * 往头文部里面添加一个CSS文件
     * @param string $css
     * @return Uuch_BaseController
     */
    public function appendCss($css) {
        $temp = $this->cdn . strtolower($css);
        $this->view->headLink()->appendStylesheet($temp);
        return $this;
    }

    /**
     * 返回JSON代码
     * @param type $data
     */
    protected function json($data) {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $this->getResponse()
                ->setHeader('Content-Type', 'application/json')
                ->appendBody(Zend_Json::encode($data));
    }

    /**
     * 直接输出HTML到桌面
     * @param type $html
     */
    protected function content($html) {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        echo $html;
    }

    /**
     * 重定向
     * @param type $action action
     * @param type $controll 控制器名称
     * @param type $param  参数
     */
    protected function redirect($action, $controll, $param = array()) {
        $this->_helper->redirector($action, $controll, NULL, $param);
    }

    /**
     * 返回当时时间
     * @return type 
     */
    protected function now() {
        return date('Y-m-d H:i:s');
    }

    /**
     * 获取当前网页的URL
     * @return string
     */
    function curPageURL() {
        $pageURL = 'http';

        if ($_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";

        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    public function noneAction() {
        $this->_redirect('/');
    }

    /**
     * 禁止模版页
     */
    protected function disableLayout() {
        $this->_helper->layout->disableLayout();
    }

    /**
     * 获取安全参数,避免HTML注入问题,并且去除首尾空格
     * @param type $paramName
     * @return type
     */
    protected function getSafeParam($paramName) {
        return trim(htmlspecialchars($this->_getParam($paramName)));
    }

    /**
     * 判断是否是POST提交的网页
     * @return bool
     */
    public function isPost() {
        $request = $this->getRequest();
        return $request->isPost();
    }

}
